package com.birdboot.controller;

import com.birdboot.entity.User;
import com.birdboot.http.HttpServletRequest;
import com.birdboot.http.HttpServletResponse;

import java.io.*;

public class UserController {
    private static File userDir;
    static {
        userDir = new File("./users");
        if(!userDir.exists()){
            userDir.mkdirs();
        }
    }

    public void reg(HttpServletRequest request , HttpServletResponse response ){
        String username  = request.getParameters("username");
        String password  = request.getParameters("password");
        String nickname  = request.getParameters("nickname");
        String age  = request.getParameters("age");
        System.out.println(username+","+password+","+nickname+","+age);
        if(
                username==null || username.isEmpty() ||
                password==null || password.isEmpty() ||
                nickname==null || nickname.isEmpty() ||
                age==null || age.isEmpty() ||
                !age.matches("[0-9]+")
        ){
            response.sendRedirect("/reg_info_error.html");
            return;
        }
        int userAge = Integer.parseInt(age);
        User user = new User(username ,password ,nickname ,userAge);
        File file = new File(userDir,username+".obj");
        if(file.exists()){
            response.sendRedirect("/reg_have_user.html");
        }else {
            try(FileOutputStream fos = new FileOutputStream(file);
                ObjectOutputStream oos = new ObjectOutputStream(fos)) {
                oos.writeObject(user);
                response.sendRedirect("/reg_success.html");
                return;
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }


    public void login(HttpServletRequest request, HttpServletResponse response) {
        String username = request.getParameters("username");
        String password = request.getParameters("password");
        if(username==null || password == null  ||username.isEmpty() || password.isEmpty()){
            response.sendRedirect("/login_info_error.html");
            return;
        }
        File file = new File(userDir,username+".obj");
        if(file.exists()){
            try (FileInputStream fis = new FileInputStream(file);
                 ObjectInputStream ois = new ObjectInputStream(fis)){
                try {
                    User user = (User)ois.readObject();
                    if(user.getPassword().equals(password)){
                        response.sendRedirect("login_success.html");
                    }else {
                        response.sendRedirect("login_fail.html");
                    }
                } catch (ClassNotFoundException e) {
                    e.printStackTrace();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }


        }else {
            response.sendRedirect("/login_info_error.html");
        }


    }
}
